const fs = require('fs');
const path = require('path');

// 确保日志目录存在
const logDir = path.join(__dirname, '../logs');
if (!fs.existsSync(logDir)) {
  fs.mkdirSync(logDir, { recursive: true });
}

// 格式化时间
function formatTime() {
  return new Date().toISOString().replace('T', ' ').substring(0, 19);
}

// 写入日志文件
function writeLogFile(filename, content) {
  const logFile = path.join(logDir, filename);
  const timestamp = formatTime();
  const logEntry = `[${timestamp}] ${content}\n`;
  
  fs.appendFileSync(logFile, logEntry, 'utf8');
}

// 日志级别
const LogLevel = {
  ERROR: 'ERROR',
  WARN: 'WARN',
  INFO: 'INFO',
  DEBUG: 'DEBUG'
};

class Logger {
  static logRequest(req, res, error = null) {
    const logData = {
      timestamp: new Date().toISOString(),
      method: req.method,
      url: req.originalUrl,
      ip: req.ip || req.connection.remoteAddress,
      userAgent: req.get('User-Agent'),
      statusCode: res.statusCode,
      responseTime: res.get('X-Response-Time'),
      error: error ? {
        message: error.message,
        stack: error.stack,
        code: error.code
      } : null
    };

    // 控制台输出
    if (error || res.statusCode >= 400) {
      console.error('🚨 [API错误]', JSON.stringify(logData, null, 2));
      // 写入错误日志文件
      writeLogFile('error.log', JSON.stringify(logData));
    } else {
      console.log('📝 [API访问]', `${req.method} ${req.originalUrl} - ${res.statusCode}`);
      // 写入访问日志文件
      writeLogFile('access.log', JSON.stringify(logData));
    }
  }

  static logDatabase(operation, sql, params, error = null, result = null) {
    const logData = {
      timestamp: new Date().toISOString(),
      operation,
      sql,
      params,
      error: error ? {
        message: error.message,
        code: error.code,
        errno: error.errno
      } : null,
      resultCount: result ? (Array.isArray(result[0]) ? result[0].length : 1) : 0
    };

    if (error) {
      console.error('💾 [数据库错误]', JSON.stringify(logData, null, 2));
      writeLogFile('database.log', JSON.stringify(logData));
    } else {
      console.log('💾 [数据库操作]', `${operation} - 影响行数: ${logData.resultCount}`);
    }
  }

  static log(level, message, data = null) {
    const logData = {
      timestamp: new Date().toISOString(),
      level,
      message,
      data
    };

    console.log(`[${level}]`, message, data || '');
    writeLogFile('app.log', JSON.stringify(logData));
  }

  // 添加缺失的logInfo方法
  static logInfo(message, data = null) {
    this.log(LogLevel.INFO, message, data);
  }

  // 添加其他常用的日志方法
  static logError(message, data = null) {
    this.log(LogLevel.ERROR, message, data);
  }

  static logWarn(message, data = null) {
    this.log(LogLevel.WARN, message, data);
  }

  static logDebug(message, data = null) {
    this.log(LogLevel.DEBUG, message, data);
  }
}

module.exports = { Logger, LogLevel };